package org.example.web;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.example.task.DataRefreshTask;
import org.example.web.websocket.ProgressSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WebServer {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebServer.class);
    private final HttpServer server;
    private final ProgressSocket progressSocket;
    private final ExecutorService taskExecutor = Executors.newSingleThreadExecutor();

    private volatile String currentJsonData;

    public WebServer(int httpPort, int wsPort, String initialJsonData) throws IOException {
        this.currentJsonData = initialJsonData;
        this.progressSocket = new ProgressSocket(wsPort);

        server = HttpServer.create(new InetSocketAddress(httpPort), 0);
        
        // API端点: 触发刷新
        server.createContext("/api/refresh", exchange -> {
            LOGGER.info("接收到刷新请求...");
            taskExecutor.submit(new DataRefreshTask(progressSocket, newJson -> {
                this.currentJsonData = newJson;
                LOGGER.info("JSON数据已更新。");
            }));
            String response = "{\"status\": \"refresh started\"}";
            exchange.sendResponseHeaders(200, response.length());
            try(OutputStream os = exchange.getResponseBody()) {
                os.write(response.getBytes());
            }
        });
        
        // 1. 创建一个处理器来提供 index.html
        server.createContext("/", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                LOGGER.info("请求主页: {}", exchange.getRequestURI());
                try (InputStream is = getClass().getClassLoader().getResourceAsStream("index.html")) {
                    if (is == null) {
                        String response = "404 (Not Found)\n";
                        exchange.sendResponseHeaders(404, response.length());
                        try (OutputStream os = exchange.getResponseBody()) {
                            os.write(response.getBytes(StandardCharsets.UTF_8));
                        }
                        return;
                    }
                    exchange.getResponseHeaders().set("Content-Type", "text/html; charset=utf-8");
                    exchange.sendResponseHeaders(200, 0); // 0 means response length is unknown
                    try (OutputStream os = exchange.getResponseBody()) {
                        final byte[] buffer = new byte[1024];
                        int count;
                        while ((count = is.read(buffer)) != -1) {
                            os.write(buffer, 0, count);
                        }
                    }
                }
            }
        });
        
        // 2. 创建一个处理器来提供 JSON 数据
        server.createContext("/analysis_results.json", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                LOGGER.info("请求JSON数据: {}", exchange.getRequestURI());
                byte[] response = currentJsonData.getBytes(StandardCharsets.UTF_8);
                exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
                exchange.sendResponseHeaders(200, response.length);
                try (OutputStream os = exchange.getResponseBody()) {
                    os.write(response);
                }
            }
        });
        
        // 3. 静态资源处理器 (Chart.js等)
        server.createContext("/static/", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                String path = exchange.getRequestURI().getPath();
                LOGGER.info("请求静态资源: {}", path);
                
                // 移除开头的 /static/
                String resourcePath = path.substring(8); // "/static/".length() = 8
                
                try (InputStream is = getClass().getClassLoader().getResourceAsStream("static/" + resourcePath)) {
                    if (is == null) {
                        String response = "404 (Not Found)\n";
                        exchange.sendResponseHeaders(404, response.length());
                        try (OutputStream os = exchange.getResponseBody()) {
                            os.write(response.getBytes(StandardCharsets.UTF_8));
                        }
                        return;
                    }
                    
                    // 设置正确的Content-Type
                    String contentType = "text/plain";
                    if (resourcePath.endsWith(".js")) {
                        contentType = "application/javascript";
                    } else if (resourcePath.endsWith(".css")) {
                        contentType = "text/css";
                    } else if (resourcePath.endsWith(".html")) {
                        contentType = "text/html";
                    }
                    
                    exchange.getResponseHeaders().set("Content-Type", contentType + "; charset=utf-8");
                    exchange.sendResponseHeaders(200, 0);
                    try (OutputStream os = exchange.getResponseBody()) {
                        final byte[] buffer = new byte[1024];
                        int count;
                        while ((count = is.read(buffer)) != -1) {
                            os.write(buffer, 0, count);
                        }
                    }
                }
            }
        });
        
        // 4. index2.html 处理器
        server.createContext("/index2.html", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                LOGGER.info("请求简化版页面: {}", exchange.getRequestURI());
                try (InputStream is = getClass().getClassLoader().getResourceAsStream("index2.html")) {
                    if (is == null) {
                        String response = "404 (Not Found)\n";
                        exchange.sendResponseHeaders(404, response.length());
                        try (OutputStream os = exchange.getResponseBody()) {
                            os.write(response.getBytes(StandardCharsets.UTF_8));
                        }
                        return;
                    }
                    exchange.getResponseHeaders().set("Content-Type", "text/html; charset=utf-8");
                    exchange.sendResponseHeaders(200, 0);
                    try (OutputStream os = exchange.getResponseBody()) {
                        final byte[] buffer = new byte[1024];
                        int count;
                        while ((count = is.read(buffer)) != -1) {
                            os.write(buffer, 0, count);
                        }
                    }
                }
            }
        });
        
        // 5. 测试页面处理器
        server.createContext("/test.html", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                LOGGER.info("请求测试页面: {}", exchange.getRequestURI());
                try (InputStream is = getClass().getClassLoader().getResourceAsStream("test_local_resources.html")) {
                    if (is == null) {
                        String response = "404 (Not Found)\n";
                        exchange.sendResponseHeaders(404, response.length());
                        try (OutputStream os = exchange.getResponseBody()) {
                            os.write(response.getBytes(StandardCharsets.UTF_8));
                        }
                        return;
                    }
                    exchange.getResponseHeaders().set("Content-Type", "text/html; charset=utf-8");
                    exchange.sendResponseHeaders(200, 0);
                    try (OutputStream os = exchange.getResponseBody()) {
                        final byte[] buffer = new byte[1024];
                        int count;
                        while ((count = is.read(buffer)) != -1) {
                            os.write(buffer, 0, count);
                        }
                    }
                }
            }
        });
    }

    public void start() {
        progressSocket.start();
        server.start();
        
        LOGGER.info("========================================================================");
        LOGGER.info("HTTP服务器已在端口 {} 启动", server.getAddress().getPort());
        LOGGER.info("WebSocket服务器已在端口 {} 启动", progressSocket.getPort());
        LOGGER.info("分析结果仪表盘已就绪。");
        LOGGER.info("可用页面:");
        LOGGER.info("  - 完整版仪表盘: http://localhost:{}/", server.getAddress().getPort());
        LOGGER.info("  - 简化版仪表盘: http://localhost:{}/index2.html", server.getAddress().getPort());
        LOGGER.info("  - 本地资源测试: http://localhost:{}/test.html", server.getAddress().getPort());
        LOGGER.info("使用 Ctrl+C 来关闭应用程序。");
        LOGGER.info("========================================================================");
    }
} 